package br.edu.ifrn.persistencia;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import br.edu.ifrn.beans.Admin;

public class AdminDAO {
Conexao conexao = Conexao.getInstance();
	
	public void inserirAdmin(Admin admin) {
		
		PreparedStatement ps = null;
		
		try {
			String query = "INSERT INTO admin VALUES (?,?)";
			
			ps= conexao.getPreparedStatement(query);
			
			ps.setString(1, admin.getMatricula());
			ps.setString(2, admin.getSenha());
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void deletarAdmin(Admin admin) {
		PreparedStatement ps= null;
		try {
			String query= "DELETE FROM admin WHERE matricula=?";
			ps= conexao.getPreparedStatement(query);
			ps.setString(1, admin.getMatricula());
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public Admin recuperarPorMatricula(String matricula) { 
		PreparedStatement ps = null;
		Admin admin = new Admin();
		try {
			String query = "SELECT * FROM admin WHERE matricula=?";
			ps = conexao.getPreparedStatement(query);
			ps.setString(1, matricula);
			ResultSet rs = ps.executeQuery();
			while (rs.next()) {
				admin.setMatricula(rs.getString("matricula"));
				admin.setSenha(rs.getString("senha"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return admin;
	}
	
	public Admin logar(String id, String senha){
		Admin admin = recuperarPorMatricula(id);
		if(senha.equals(admin.getSenha()))
			return admin;
		else
			return null;
			
	}

	public void editarSenha(Admin admin){
		PreparedStatement ps = null;
		try {
			String query = "UPDATE admin SET senha=? WHERE matricula=?";
			
			ps = conexao.getPreparedStatement(query);

			ps.setString(1, admin.getSenha());
			ps.setString(2, admin.getMatricula());
			
			ps.executeUpdate();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
